package com.zxl.study.support;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.zxl.study.entities.MetaDatabase;
import io.micrometer.core.instrument.util.StringUtils;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JdbcUtil {

    /**
     * 获取数据库连接
     *
     * @param database 数据库对象
     * @param strategy 数据库策略类
     * @return java.sql.Connection
     */
    public static Connection getConnection(MetaDatabase database, Strategy<DruidPooledConnection> strategy) {
        try {
            String userName = database.getUser();
            String passwd = database.getPasswd();
            //获得连接地址
            String url = database.getJdbcUrl();
            //设置驱动
            strategy.setDriver();
            DriverManager.setLoginTimeout(0);
            return DriverManager.getConnection(url, userName, passwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 释放资源的方法
     *
     * @param conn
     * @param stmt
     * @param rs
     * @return void
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        closeRs(rs);
        closeStmt(stmt);
        close(conn);
    }

    /**
     * 释放资源的方法
     *
     * @param conn
     * @return void
     */
    public static void close(Connection conn) {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeStmt(Statement stmt) {
        try {
            if (stmt != null && !stmt.isClosed()) {
                stmt.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void closeRs(ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
